package org.zwy.gradetrack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.Course;
import org.zwy.gradetrack.entity.CourseGoalAchievement;
import org.zwy.gradetrack.service.CourseGoalAchievementService;
import org.zwy.gradetrack.service.CourseService;
import org.zwy.gradetrack.vo.CourseGoalAchievementVo;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 课程目标达成度管理控制器
 */
@RestController
@RequestMapping("/api/course-goal-achievements")
public class CourseGoalAchievementController {

    @Autowired
    private CourseGoalAchievementService courseGoalAchievementService;

    @Autowired
    private CourseService courseService;

    /**
     * 获取达成度列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER'" +
            ")")
    public Result<List<CourseGoalAchievementVo>> getAchievementList(
            @RequestParam(required = false) Integer courseId,
            @RequestParam(required = false) Integer academicYear,
            @RequestParam(required = false) Integer semester) {
        
        // 检查课程是否存在（如果指定了courseId）
        if (courseId != null && !courseService.lambdaQuery()
                .eq(Course::getId, courseId)
                .exists()) {
            return Result.error(404, "课程不存在");
        }

        // 始终调用带有指标点关联的查询方法
        List<CourseGoalAchievementVo> achievements = courseGoalAchievementService.getAchievementsWithIndicator(
                courseId, academicYear, semester);
        
        return Result.success(achievements);
    }

    /**
     * 创建达成度
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<CourseGoalAchievement> createAchievement(@RequestBody CourseGoalAchievement achievement) {
        // 检查课程是否存在
        if (!courseService.lambdaQuery()
                .eq(Course::getId, achievement.getCourseId())
                .exists()) {
            return Result.error(404, "课程不存在");
        }

        // 检查是否已存在相同课程、学年、学期的记录
        if (courseGoalAchievementService.lambdaQuery()
                .eq(CourseGoalAchievement::getCourseId, achievement.getCourseId())
                .eq(CourseGoalAchievement::getAcademicYear, achievement.getAcademicYear())
                .eq(CourseGoalAchievement::getSemester, achievement.getSemester())
                .exists()) {
            return Result.error(400, "该课程在指定学年学期的达成度记录已存在");
        }

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        achievement.setCreateTime(now);
        achievement.setUpdateTime(now);

        // 保存达成度信息
        courseGoalAchievementService.save(achievement);
        return Result.success(achievement);
    }

    /**
     * 更新达成度
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<CourseGoalAchievement> updateAchievement(@PathVariable Long id, @RequestBody CourseGoalAchievement achievement) {
        // 检查达成度是否存在
        if (!courseGoalAchievementService.lambdaQuery()
                .eq(CourseGoalAchievement::getId, id)
                .exists()) {
            return Result.error(404, "达成度不存在");
        }

        // 检查课程是否存在
        if (!courseService.lambdaQuery()
                .eq(Course::getId, achievement.getCourseId())
                .exists()) {
            return Result.error(404, "课程不存在");
        }

        // 检查是否与其他记录冲突
        if (courseGoalAchievementService.lambdaQuery()
                .eq(CourseGoalAchievement::getCourseId, achievement.getCourseId())
                .eq(CourseGoalAchievement::getAcademicYear, achievement.getAcademicYear())
                .eq(CourseGoalAchievement::getSemester, achievement.getSemester())
                .ne(CourseGoalAchievement::getId, id)
                .exists()) {
            return Result.error(400, "该课程在指定学年学期的达成度记录已存在");
        }

        // 更新达成度信息
        achievement.setId(id);
        achievement.setUpdateTime(LocalDateTime.now());
        courseGoalAchievementService.updateById(achievement);
        return Result.success(achievement);
    }

    /**
     * 删除达成度
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<Void> deleteAchievement(@PathVariable Integer id) {
        // 检查达成度是否存在
        if (!courseGoalAchievementService.lambdaQuery()
                .eq(CourseGoalAchievement::getId, id)
                .exists()) {
            return Result.error(404, "达成度不存在");
        }

        // 删除达成度
        courseGoalAchievementService.removeById(id);
        return Result.success();
    }

    /**
     * 获取达成度详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<CourseGoalAchievement> getAchievementDetail(@PathVariable Integer id) {
        CourseGoalAchievement achievement = courseGoalAchievementService.getById(id);
        if (achievement == null) {
            return Result.error(404, "达成度不存在");
        }
        return Result.success(achievement);
    }
} 